package apis

import (
	"github.com/gin-gonic/gin"
	"github.com/gin-gonic/gin/binding"
	"github.com/go-admin-team/go-admin-core/sdk/api"
	"net/http"
	"strconv"
	"tuowei.com/app/admin/models"
	"tuowei.com/pkg/xlog"
)

type ESignOrder struct {
	api.Api
}

type ESignCallbackReq struct {
	Action            string `json:"action"`
	Timestamp         int64  `json:"timestamp"`
	SignFlowID        string `json:"signFlowId"`
	CustomBizNum      string `json:"customBizNum"`
	SignOrder         int    `json:"signOrder"`
	OperateTime       int64  `json:"operateTime"`
	SignResult        int    `json:"signResult"`
	ResultDescription string `json:"resultDescription"`
	Operator          struct {
		PsnID      string `json:"psnId"`
		PsnAccount struct {
			AccountMobile string `json:"accountMobile"`
		} `json:"psnAccount"`
	} `json:"operator"`
}

type action string

const (
	SIGN_MISSON_COMPLETE action = "SIGN_MISSON_COMPLETE"
	SIGN_FLOW_COMPLETE   action = "SIGN_FLOW_COMPLETE"
	OPERATOR_READ        action = "OPERATOR_READ"
	TRANSMISS_SIGN       action = "TRANSMISS_SIGN"
	FILE_UNAVAILABLE     action = "FILE_UNAVAILABLE"
)

func (o ESignOrder) ESignCallback(ctx *gin.Context) {
	xlog.Info("esign callback start")
	req := new(ESignCallbackReq)
	orderIdStr := ctx.Query("orderId")
	if orderIdStr == "" {
		ctx.JSON(http.StatusBadRequest, "no orderId")
		return
	}
	orderId, err := strconv.Atoi(orderIdStr)
	if err != nil {
		xlog.Error(err)
		ctx.JSON(http.StatusBadRequest, err.Error())
		return
	}
	err = o.MakeContext(ctx).MakeOrm().Bind(req, binding.JSON).Errors
	if err != nil {
		xlog.Error(err)
		ctx.JSON(http.StatusBadRequest, err.Error())
		return
	}
	xlog.Info(req)
	if req.Action == string(SIGN_MISSON_COMPLETE) {
		// 通过flowid查处订单
		o.Orm.Table(models.OfflineOrder{}.TableName()).Where("id = ?", orderId).Update("signed", 1)
	}
	ctx.JSON(http.StatusOK, gin.H{
		"code": 200,
		"msg":  "success",
	})
	return
}
